package com.lhdx.practical.controllers;

import com.alibaba.fastjson.JSONObject;
import com.lhdx.practical.bean.Depart;
import com.lhdx.practical.bean.Menu;
import com.lhdx.practical.bean.MenuConfig;
import com.lhdx.practical.service.DepartService;
import com.lhdx.practical.service.MenuConfigService;
import com.lhdx.practical.service.MenuService;
import com.lhdx.practical.service.PersonService;
import com.lhdx.practical.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/function/depart")
public class DepartController {
    @Autowired
    private DepartService departService;
    @Autowired
    private MenuService menuService;
    @Autowired
    private MenuConfigService menuConfigService;
    @Autowired
    private PersonService personService;
    @Autowired
    private HttpServletRequest request;

    /**
     * 学年管理列表
     * @return
     */
    @GetMapping("/list")
    public ModelAndView list() {
        List<Depart> departs = departService.findAllByPid(0);
        return new ModelAndView("depart/list").addObject("departs",departs);
    }

    /**
     * 班级管理列表
     * @return
     */
    @GetMapping("/classlist")
    public ModelAndView classlist() {
        int page = StrUtils.getInt(request,"p",1);
        Map<String,String> searchmap = new HashMap<>();
        PageVo<Depart> pageResult = new PageVo<Depart>(page,searchmap,departService.getResultList(page,Constants.pagesize));
        return new ModelAndView("depart/classlist").addObject("pageResult",pageResult);
    }

    /**
     * 学生管理-班级管理列表
     * @return
     */
    @GetMapping("/stuclasslist")
    public ModelAndView stuclasslist() {
        List<Depart> departs = departService.findAllByPidNotOrderBySortDesc(0);
        return new ModelAndView("depart/stuclasslist").addObject("departs",departs);
    }

    private void digui(List<Depart> departs,long pid){
        List<Depart> departList = departService.findAllByPid(pid);
        for(Depart depart : departList){
            departs.add(depart);
            this.digui(departs,depart.getId());
        }

    }

    @GetMapping("/add")
    public ModelAndView add() {
        return new ModelAndView("depart/add")
                .addObject("departs",departService.findAllByPid(0));
    }

    /**
     * 新建学年
     * @return
     */
    @GetMapping("/addgrade")
    public ModelAndView addgrade() {
        return new ModelAndView("depart/addgrade")
                .addObject("departs",departService.findAllByPid(0))
                .addObject("menulist",menuService.findAllByPid(0))
                .addObject("teacherList",personService.findAllByTypeAndGradeid(1,0));
    }

    @CrossOrigin
    @PostMapping("toaddgrade")
    @ResponseBody
    public String toaddgrade(long id,String departname,int sort,String menuids,String teachers,String teacherNames) {
        JSONObject jsonObject = new JSONObject();
        try {
            //添加 保存学年
            Depart depart = null;
            if(id == 0){
                if(departService.countAllByDepartname(departname) > 0){
                    jsonObject = JsonUtils.JsonReturn(Constants.ERROR,"学年名称已存在","");
                }else{
                    depart = new Depart(0,"",departname,sort,0);
                }

            }else{
                depart = departService.findById(id);
                depart.setDepartname(departname);
                depart.setPid(0);
                depart.setSort(sort);
                depart.setLevel(0);
            }
            if(depart != null){
                departService.save(depart);
                //添加学年单元配置
                menuConfigService.deleteAllByGradeid(depart.getId());
                if(menuids.indexOf(",") > -1){
                    String[] menuid = menuids.split(",");
                    String[] teacher = teachers.split(",");
                    String[] teacherName = teacherNames.split(",");
                    for(int i=0;i<menuid.length;i++){
                        saveMenu(depart.getId(),Long.parseLong(menuid[i]),Long.parseLong(teacher[i]),teacherName[i]);
                    }
                }else{
                    saveMenu(depart.getId(),Long.parseLong(menuids),Long.parseLong(teachers),teacherNames);
                }
                jsonObject = JsonUtils.JsonReturn(Constants.SUCCESS,"学年添加成功","");
            }

        }catch (Exception e) {
            e.printStackTrace();
            jsonObject = JsonUtils.JsonReturn(Constants.ERROR,"学年添加失败","");
        }
        return jsonObject.toString();
    }

    @GetMapping("/update")
    public ModelAndView update(long id) {
        Depart depart = departService.findById(id);
        return new ModelAndView("depart/update")
                .addObject("departs",departService.findAllByPid(0))
                .addObject("depart",depart);
    }

    @GetMapping("/menuconfig")
    public ModelAndView menuconfig(long gradeid) {
        Depart depart = departService.findById(gradeid);
        List<MenuConfig> configs = menuConfigService.findAllByGradeid(gradeid);
        return new ModelAndView("depart/menuconfig")
                .addObject("depart",depart)
                .addObject("configs",configs)
                .addObject("menulist",menuService.findAllByPid(0))
                .addObject("teacherList",personService.findAllByTypeAndGradeid(1,0));
    }

    /**
     * 修改年级
     * @param id
     * @return
     */
    @GetMapping("/updategrade")
    public ModelAndView updategrade(long id) {
        Depart depart = departService.findById(id);
        List<MenuConfig> configs = menuConfigService.findAllByGradeid(id);
        return new ModelAndView("depart/updategrade")
                .addObject("depart",depart)
                .addObject("configs",configs)
                .addObject("menulist",menuService.findAllByPid(0))
                .addObject("teacherList",personService.findAllByTypeAndGradeid(1,0));
    }

    @CrossOrigin
    @PostMapping("setMenuConfig")
    @ResponseBody
    public String setMenuConfig(long gradeid,String menuids,String teachers,String teacherNames) {
        JSONObject jsonObject = new JSONObject();
        try {
            menuConfigService.deleteAllByGradeid(gradeid);
            if(menuids.indexOf(",") > -1){
                String[] menuid = menuids.split(",");
                String[] teacher = teachers.split(",");
                String[] teacherName = teacherNames.split(",");
                for(int i=0;i<menuid.length;i++){
                    saveMenu(gradeid,Long.parseLong(menuid[i]),Long.parseLong(teacher[i]),teacherName[i]);
                }
            }else{
                saveMenu(gradeid,Long.parseLong(menuids),Long.parseLong(teachers),teacherNames);
            }
            jsonObject = JsonUtils.JsonReturn(Constants.SUCCESS,"单元配置成功","");
        }catch (Exception e) {
            e.printStackTrace();
            jsonObject = JsonUtils.JsonReturn(Constants.ERROR,"单元配置失败","");
        }
        return jsonObject.toString();
    }

    /**
     * 保存目录
     * @param gradeid
     * @param menuid
     * @param teacherid
     * @param teachername
     */
    void saveMenu(long gradeid,long menuid,long teacherid,String teachername){
        Depart depart = departService.findById(gradeid);
        Menu menu = menuService.findById(menuid);
        MenuConfig menuConfig = new MenuConfig(depart,menu,teacherid,teachername);
        menuConfigService.save(menuConfig);
    }




    @CrossOrigin
    @PostMapping("toadd")
    @ResponseBody
    public String toadd(long id,long pid,String departname,int sort) {
        JSONObject jsonObject = new JSONObject();
        try {
            //判断组织架构级别
            Depart parentdepart = null;
            int level = 0;
            if(pid != 0){
                parentdepart = departService.findById(pid);
                if(parentdepart != null){
                    level = parentdepart.getLevel() +1;
                }
            }
            Depart depart = null;
            if(id == 0){
                depart = new Depart(pid,parentdepart.getDepartname(),departname,sort,level);
            }else{
                depart = departService.findById(id);
                depart.setDepartname(departname);
                depart.setPidname(parentdepart.getDepartname());
                depart.setPid(pid);
                depart.setSort(sort);
                depart.setLevel(level);
            }
            departService.save(depart);
            jsonObject = JsonUtils.JsonReturn(Constants.SUCCESS,"组织架构添加成功","");
        }catch (Exception e) {
            e.printStackTrace();
            jsonObject = JsonUtils.JsonReturn(Constants.ERROR,"组织架构添加失败","");
        }
        return jsonObject.toString();
    }

    @CrossOrigin
    @PostMapping("delete")
    @ResponseBody
    public String delete(long departid) {
        JSONObject jsonObject = new JSONObject();
        try {
            if(departService.countAllByPid(departid) > 0){
                jsonObject = JsonUtils.JsonReturn(Constants.ERROR,"请先删除班级","");
            }else if(personService.countAllByDepartid(departid) > 0){
                jsonObject = JsonUtils.JsonReturn(Constants.ERROR,"请先删除班级下的学生","");
            }else{
                departService.deleteById(departid);
                jsonObject = JsonUtils.JsonReturn(Constants.SUCCESS,"删除成功","");
            }
        }catch (Exception e) {
            e.printStackTrace();
            jsonObject = JsonUtils.JsonReturn(Constants.ERROR,"删除失败","");
        }
        return jsonObject.toString();
    }


    @CrossOrigin
    @PostMapping("getDepartByPid")
    @ResponseBody
    public String getDepartByPid(long departid) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject = JsonUtils.JsonReturn(Constants.SUCCESS,"查询成功", GsonUtils.toJsonWithGson(departService.findAllByPid(departid)));
        }catch (Exception e) {
            e.printStackTrace();
            jsonObject = JsonUtils.JsonReturn(Constants.ERROR,"查询失败","");
        }
        return jsonObject.toString();
    }
}
